import { getDiaryList, saveDiary } from '../../models/diary'
import { formatFullDateTime, formatDate, generateUniqueId, showToast } from '../../utils/util'

Page({
  // 页面私有动画对象
  dateAnimation: null as any,
  contentAnimation: null as any,
  moodAnimation: null as any,
  buttonAnimation: null as any,
  indicatorAnimation: null as any,
  // 输入防抖计时器
  inputDebounceTimer: null as any,
  
  data: {
    content: '',
    contentLength: 0,
    selectedMood: '',
    currentDate: '',
    isValid: false,
    isSaving: false,
    saveAnimationPlaying: false,
    animationData: {} as any,
    dateAnimation: {} as any,
    contentAnimation: {} as any,
    moodAnimation: {} as any,
    buttonAnimation: {} as any,
    indicatorAnimation: {} as any,
    todayDiaryCount: 0,
    isLoaded: false,
    pageReady: false,
    autoFocus: false
  },
  
  onLoad() {
    // 设置当前日期
    const now = new Date()
    this.setData({
      currentDate: formatFullDateTime(now)
    })
    
    // 初始化动画 - 将动画初始化移到最前面
    this.initAnimations()
    
    // 检查今日日记数量
    this.countTodayDiaries()
    
    // 检查是否有草稿
    this.loadDraft()
    
    // 页面加载完成后显示
    setTimeout(() => {
      this.setData({
        isLoaded: true
      })
      
      // 当页面准备好后再设置自动聚焦，避免初次加载动画时的跳动
      setTimeout(() => {
        this.setData({
          autoFocus: true
        })
        // 添加轻微振动反馈，提示用户页面已准备好
        wx.vibrateShort({ type: 'light' })
      }, 500)
    }, 100)
  },
  
  onShow() {
    // 页面显示时可以执行其他逻辑
    this.validateForm()
    
    if (!this.data.pageReady) {
      // 播放元素入场动画
      this.playEntranceAnimations()
      this.setData({
        pageReady: true
      })
    } else {
      // 重新计算今日日记数量
      this.countTodayDiaries()
    }
  },
  
  onHide() {
    // 页面隐藏时保存草稿
    this.saveDraft()
  },
  
  // 初始化动画对象
  initAnimations() {
    this.dateAnimation = wx.createAnimation({
      duration: 800,
      timingFunction: 'ease-out',
      delay: 200
    })
    
    this.contentAnimation = wx.createAnimation({
      duration: 800,
      timingFunction: 'ease-out',
      delay: 400
    })
    
    this.moodAnimation = wx.createAnimation({
      duration: 800,
      timingFunction: 'ease-out',
      delay: 600
    })
    
    this.buttonAnimation = wx.createAnimation({
      duration: 800,
      timingFunction: 'ease-out',
      delay: 800
    })
    
    this.indicatorAnimation = wx.createAnimation({
      duration: 400,
      timingFunction: 'ease-out'
    })
  },
  
  // 播放元素入场动画
  playEntranceAnimations() {
    // 初始状态
    this.dateAnimation.opacity(0).translateY(30).step({ duration: 0 })
    this.contentAnimation.opacity(0).translateY(30).step({ duration: 0 })
    this.moodAnimation.opacity(0).translateY(30).step({ duration: 0 })
    this.buttonAnimation.opacity(0).translateY(30).step({ duration: 0 })
    
    // 设置初始状态
    this.setData({
      dateAnimation: this.dateAnimation.export(),
      contentAnimation: this.contentAnimation.export(),
      moodAnimation: this.moodAnimation.export(),
      buttonAnimation: this.buttonAnimation.export()
    })
    
    // 播放动画
    setTimeout(() => {
      this.dateAnimation.opacity(1).translateY(0).step()
      this.contentAnimation.opacity(1).translateY(0).step()
      this.moodAnimation.opacity(1).translateY(0).step()
      this.buttonAnimation.opacity(1).translateY(0).step()
      
      this.setData({
        dateAnimation: this.dateAnimation.export(),
        contentAnimation: this.contentAnimation.export(),
        moodAnimation: this.moodAnimation.export(),
        buttonAnimation: this.buttonAnimation.export()
      })
    }, 100)
  },
  
  // 计算今日日记数量
  countTodayDiaries() {
    const diaryList = getDiaryList()
    const today = formatDate(new Date())
    
    // 过滤出今天的日记
    const todayDiaries = diaryList.filter(diary => {
      const diaryDate = diary.date.split(' ')[0] // 提取日期部分
      return diaryDate.includes(today.split('-')[0] + '年' + 
             today.split('-')[1] + '月' + 
             today.split('-')[2] + '日')
    })
    
    this.setData({
      todayDiaryCount: todayDiaries.length
    })
  },
  
  // 输入框获取焦点
  onFocus() {
    this.contentAnimation.scale(1.02).step({ duration: 200 })
    this.setData({
      contentAnimation: this.contentAnimation.export()
    })
    
    // 轻微触觉反馈
    wx.vibrateShort({ type: 'light' })
  },
  
  // 输入框失去焦点
  onBlur() {
    this.contentAnimation.scale(1).step()
    this.setData({
      contentAnimation: this.contentAnimation.export()
    })
  },
  
  // 处理内容输入 - 由于使用了model:value，此方法仅用于更新计数和验证
  onContentInput(e: any) {
    // 注意: 使用了model:value后，content值会自动更新，这里只需处理contentLength
    const content = e.detail.value || ''
    
    // 记录输入事件，用于调试
    console.log('输入事件触发', {
      inputValue: content,
      currentValue: this.data.content,
      valueLength: content.length
    })
    
    // 双重保险：确保content值是最新的
    // 这样可以避免model:value绑定可能存在的问题
    if (content !== this.data.content) {
      this.setData({
        content: content
      })
    }
    
    this.setData({
      contentLength: content.length
    })
    
    this.validateForm()
    
    // 自动保存草稿（延迟执行以提高性能）
    if (this.inputDebounceTimer) {
      clearTimeout(this.inputDebounceTimer)
    }
    
    this.inputDebounceTimer = setTimeout(() => {
      this.saveDraft()
    }, 1000)
    
    // 确保返回值，避免输入问题
    return content
  },
  
  // 选择心情
  selectMood(e: any) {
    const mood = e.currentTarget.dataset.mood as string
    
    // 如果点击当前选中的表情，则取消选择
    if (this.data.selectedMood === mood) {
      this.setData({
        selectedMood: ''
      })
      
      // 更新表单验证
      this.validateForm()
      
      // 触觉反馈 - 取消选择
      wx.vibrateShort({ type: 'light' })
      
      return
    }
    
    // 创建动画效果
    const animation = wx.createAnimation({ duration: 300 })
    animation.scale(1.2).step()
    animation.scale(1.0).step()
    
    this.setData({
      selectedMood: mood,
      animationData: animation.export()
    })
    
    this.validateForm()
    
    // 触觉反馈 - 选择成功
    wx.vibrateShort({ type: 'medium' })
  },
  
  // 验证表单
  validateForm() {
    const { content, selectedMood } = this.data
    const isValid = content.trim().length > 0 && selectedMood !== ''
    
    // 确保buttonAnimation已初始化
    if (this.data.isValid !== isValid && this.buttonAnimation) {
      // 按钮动画
      if (isValid) {
        this.buttonAnimation.scale(1.05).step({ duration: 200 })
        this.buttonAnimation.scale(1).step({ duration: 200 })
      }
      
      this.setData({ 
        isValid,
        buttonAnimation: isValid ? this.buttonAnimation.export() : this.data.buttonAnimation
      })
    } else {
      // 仅更新状态，不执行动画
      if (this.data.isValid !== isValid) {
        this.setData({ isValid })
      }
    }
  },
  
  // 保存日记
  saveDiaryEntry() {
    if (this.data.isSaving) return
    
    const { content, selectedMood, currentDate, isValid } = this.data
    
    if (!isValid) {
      if (!content.trim()) {
        showToast('请输入日记内容')
      } else if (!selectedMood) {
        showToast('请选择今天的心情')
      }
      return
    }
    
    // 设置保存状态
    this.setData({ 
      isSaving: true,
      saveAnimationPlaying: true 
    })
    
    // 创建日记对象
    const diaryEntry = {
      id: generateUniqueId(),
      content: content.trim(),
      mood: selectedMood,
      date: currentDate,
      timestamp: Date.now()
    }
    
    // 保存动画
    this.buttonAnimation.scale(0.95).step({ duration: 200 })
    this.setData({
      buttonAnimation: this.buttonAnimation.export()
    })
    
    // 触觉反馈
    wx.vibrateLong({
      success: () => {
        console.log('保存振动反馈')
      }
    })
    
    // 保存日记
    const success = saveDiary(diaryEntry)
    
    if (success) {
      // 移除草稿
      this.clearDraft()
      
      // 保存成功提示
      showToast('保存成功', 'success')
      
      // 更新今日日记计数
      this.countTodayDiaries()
      
      // 清空输入
      this.setData({
        content: '',
        contentLength: 0,
        selectedMood: '',
        isValid: false
      })
      
      // 播放成功动画
      this.playSuccessAnimation()
      
      // 延迟跳转回首页
      setTimeout(() => {
        this.setData({ isSaving: false })
        wx.switchTab({
          url: '/pages/index/index'
        })
      }, 1500)
    } else {
      this.buttonAnimation.scale(1).step({ duration: 200 })
      this.setData({ 
        isSaving: false,
        buttonAnimation: this.buttonAnimation.export()
      })
      showToast('保存失败，请重试', 'error')
    }
  },
  
  // 保存成功动画
  playSuccessAnimation() {
    // 内容区域动画
    this.contentAnimation.opacity(0.3).translateY(-30).scale(0.98).step({ duration: 400 })
    
    // 心情区域动画
    this.moodAnimation.opacity(0.3).translateY(-30).scale(0.98).step({ duration: 400 })
    
    // 按钮动画
    this.buttonAnimation.scale(1.05).step({ duration: 200 })
    this.buttonAnimation.scale(1).step({ duration: 200 })
    
    this.setData({
      contentAnimation: this.contentAnimation.export(),
      moodAnimation: this.moodAnimation.export(),
      buttonAnimation: this.buttonAnimation.export()
    })
    
    // 重置动画状态
    setTimeout(() => {
      this.contentAnimation.opacity(1).translateY(0).scale(1).step({ duration: 300 })
      this.moodAnimation.opacity(1).translateY(0).scale(1).step({ duration: 300 })
      
      this.setData({
        contentAnimation: this.contentAnimation.export(),
        moodAnimation: this.moodAnimation.export()
      })
    }, 800)
  },
  
  // 保存草稿
  saveDraft() {
    const { content, selectedMood } = this.data
    if (content.trim() || selectedMood) {
      try {
        wx.setStorageSync('diary_draft', {
          content,
          selectedMood,
          timestamp: Date.now()
        })
      } catch (e) {
        console.error('保存草稿失败', e)
      }
    }
  },
  
  // 加载草稿
  loadDraft() {
    try {
      const draft = wx.getStorageSync('diary_draft')
      if (draft && draft.timestamp) {
        // 检查草稿是否是今天的
        const now = new Date()
        const draftDate = new Date(draft.timestamp)
        
        if (now.toDateString() === draftDate.toDateString()) {
          this.setData({
            content: draft.content || '',
            contentLength: (draft.content || '').length,
            selectedMood: draft.selectedMood || ''
          })
          
          this.validateForm()
          
          // 提示用户已加载草稿
          wx.showToast({
            title: '已恢复未完成的日记',
            icon: 'none',
            duration: 2000
          })
        }
      }
    } catch (e) {
      console.error('加载草稿失败', e)
    }
  },
  
  // 清除草稿
  clearDraft() {
    try {
      wx.removeStorageSync('diary_draft')
    } catch (e) {
      console.error('清除草稿失败', e)
    }
  },
  
  // 点击内容区域聚焦文本框
  focusTextarea() {
    // 先清除当前的焦点状态
    this.setData({
      autoFocus: false
    })
    
    // 设置焦点
    setTimeout(() => {
      this.setData({
        autoFocus: true
      })
      
      // 添加轻微振动反馈
      wx.vibrateShort({ type: 'light' })
      
      // 确保界面更新后再次尝试聚焦
      setTimeout(() => {
        const query = wx.createSelectorQuery()
        query.select('#diary-textarea').node(res => {
          const textarea = res.node
          if (textarea) {
            textarea.focus({
              cursor: -1 // 光标定位到文本末尾
            })
          } else {
            console.log('未找到文本框节点')
          }
        }).exec()
      }, 100)
    }, 50)
  }
}) 